﻿using Clancy.Interfaces;
using Ninject;
using System;

namespace Clancy.Bl
{
    internal class OperationAdapterFactory : IOperationAdapterFactory, IDisposable
    {
        private readonly IRecordingManager m_RecordingManager;
        private readonly IServerConnectionLogic m_ServerConnectionLogic;
        private readonly ISurveilanceStorage m_Storage;
        private readonly ISurveilanceLogic m_SurveilanceLogic;
        private readonly IVideoSourceFactory m_VideoSourceFactory;
        private readonly IVideoSourceProvider m_VideoSourceProvider;
        private IOperationAdapter m_CurrentAdapter;

        public OperationAdapterFactory(IKernel kernel)
        {
            m_ServerConnectionLogic = kernel.Get<IServerConnectionLogic>();
            m_Storage = kernel.Get<ISurveilanceStorage>();
            m_SurveilanceLogic = kernel.Get<ISurveilanceLogic>();
            m_VideoSourceProvider = kernel.Get<IVideoSourceProvider>();
            m_VideoSourceFactory = kernel.Get<IVideoSourceFactory>();
            m_RecordingManager = kernel.Get<IRecordingManager>();
        }

        public IOperationAdapter CurrentAdapter
        {
            get { return m_CurrentAdapter; }
        }

        public void Dispose()
        {
            DisposeOperationsAdapter();
        }

        public IOperationAdapter SwitchToOnlineMode()
        {
            DisposeOperationsAdapter();

            m_CurrentAdapter = new OnlineOperationAdapter(m_ServerConnectionLogic, m_Storage);

            return CurrentAdapter;
        }

        public IOperationAdapter SwitchToStandAloneMode()
        {
            DisposeOperationsAdapter();

            m_CurrentAdapter = new StandAloneOperationAdapter(m_SurveilanceLogic, m_Storage, m_VideoSourceProvider, m_VideoSourceFactory, m_RecordingManager);
            return CurrentAdapter;
        }

        private void DisposeOperationsAdapter()
        {
            if (CurrentAdapter != null)
            {
                CurrentAdapter.Dispose();
            }
            m_Storage.SurveilanceObjects.Clear();
        }
    }
}